﻿using System;
using System.Collections.Generic;
using System.Linq;

using BEX.DataAccess;

namespace BEX.RuleMonitor
{
    public class NotificationQueue
    {
        public int Id { get; set; }

        public string Message { get; set; }

        public DateTime TimeStamp { get; set; }

        public int RuleId { get; set; }

        public string RuleType { get; set; }

        public int AccountId { get; set; }

        public int NotificationType { get; set; }

        private AlertRule _toNotify;

        public NotificationQueue(string message, int ruleId, string ruleType, int account, AlertRule tonotify)
        {
            Message = message;
            TimeStamp = DateTime.Now;
            RuleId = ruleId;
            RuleType = ruleType;
            AccountId = account;
            _toNotify = tonotify;
        }

        public bool IsNotificationAllowed()
        {
            var _coolDown = _toNotify.GetCoolDownTime(AccountId);
            var _last = _toNotify.LastNofiticationTime(AccountId);

            var _diff = DateTime.Now - _last;

            if (_diff.TotalSeconds > _coolDown)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Create()
        {
            if (IsNotificationAllowed())
            {
                var _context = new BTCDataClassesDataContext();
                var _acc = GetQueueTable();
                var _n = new NOTIFICATION_QUEUE();

                _n.ACCOUNT_ID = AccountId;
                _n.MESSAGE = Message;
                _n.NOTIFICATION_TYPE_ID = 1;
                _n.RULE_ID = RuleId;
                _n.RULE_TYPE = RuleType;
                _n.TIMESTAMP = TimeStamp;

                _acc.InsertOnSubmit(_n);
                _acc.Context.SubmitChanges();
            }
        }

        public static System.Data.Linq.Table<NOTIFICATION_QUEUE> GetQueueTable()
        {
            var _context = new BTCDataClassesDataContext();

            return _context.GetTable<NOTIFICATION_QUEUE>();
        }
    }
}
